import os
from google.cloud import storage
from google.oauth2 import service_account
from googleapiclient.discovery import build


def create_gce_instance(project='daycost', cmd=None, machine_type='e2-small'):
    credentials = service_account.Credentials.from_service_account_file('./%s.json' % project)
    service = build('compute', 'v1', credentials=credentials)
    image_response = service.images().getFromFamily(
        project='ubuntu-os-cloud', family='ubuntu-2004-lts').execute()
    source_disk_image = image_response['selfLink']

    startup_script = cmd if cmd else 'cd /root && echo 11111 > 1.txt'
    machine_uri = 'https://www.googleapis.com/compute/v1/projects/%s/zones/asia-east2-a/machineTypes/%s' % (
    project, machine_type),

    config = {
        'name': 'cc-api',
        # 'machineType': 'e2-small',
        'machineType': machine_uri,
        # Specify the boot disk and the image to use as a source.
        'disks': [
            {
                'boot': True,
                'autoDelete': True,
                'initializeParams': {
                    'sourceImage': source_disk_image,
                }
            }
        ],

        # Specify a network interface with NAT to access the public
        # internet.
        'networkInterfaces': [{
            'network': 'global/networks/default',
            'accessConfigs': [
                {'type': 'ONE_TO_ONE_NAT', 'name': 'External NAT'}
            ]
        }],

        # Allow the instance to access cloud storage and logging.
        'serviceAccounts': [{
            'email': 'default',
            'scopes': [
                'https://www.googleapis.com/auth/devstorage.read_write',
            ]
        }],

        # Metadata is readable from the instance and allows you to
        # pass configuration from deployment scripts to instances.
        'metadata': {
            'items': [{
                # Startup script is automatically executed by the
                # instance upon startup.
                'key': 'startup-script',
                'value': startup_script
            }]
        }
    }

    result = service.instances().insert(
        project=project,
        zone='asia-east2-a',
        body=config).execute()
    print(result)
    # for ii in iis:
    #     print(ii)
